<?php
/**
 * Created by PhpStorm.
 * User: Echa
 * Date: 2016/9/7
 * Time: 14:01
 */
namespace YMApi\Model;
use Think\Model;
use Think\Template\Driver\Mobile;

class GoodspreselltimeModel extends Model
{
    protected $tableName = 'goods_presell_time';
    
    
    /*
     * 检查该订单商品是否在发货时间分段内
     * */
    public function check_goodspreselltime($goods_id,$paytime){
        $where=array('goods_id'=>$goods_id,'delivery_time'=>$paytime);
        $res=$this->where($where)->order('delivery_time asc,endval asc')->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    
    /*
     * 检查预售商品是否设置发货配送时间
     * */
    public function check_shipping_goodspreselltime($goods_id){
        $count=$this->where(array('goods_id'=>$goods_id))->count();
        if($count>0){
            return true;
        }else{
            return false;
        }
    }
    
    /*
     * 根据商品ID查询预售发货时间列表
     * */
    public function get_presell_goods_time($goods_id){
           $res=$this->where(array('goods_id'=>$goods_id))->select();
           if($res){
               return $res;
           }else{
               return false;
           }
    }
    
    /*
     * 根据预售商品ID查询该商品销售量
     * 
     * */
    public function get_presell_goods_sales($goods_id,$best_time){
        $count=$order_goods_mod=M('order_goods as og')->field('SUM(og.goods_number) as goods_num')->join(C('DB_PREFIX').'order_info as oi on og.order_id=oi.order_id')
        //->where('og.goods_id='.$goods_id.' and og.is_presell=1 and oi.shipping_status=0 and oi.pay_status=2 and oi.best_time='.$best_time)
        ->where('og.goods_id='.$goods_id.' and og.is_presell=1 and oi.shipping_status=0 and oi.pay_status=2 and og.buckle_inventory=0')
        ->select();
        if($count[0]['goods_num']>=0){
            return $count[0]['goods_num'];
        }else{
            return 0;
        }
    }
    
    /*
     * 检查预售商品属于哪个发货时间
     * */
    public function check_shippingtime($goods_id,$paytime){
        $slesnum=$this->get_presell_goods_sales($goods_id,$paytime);
        if(!$slesnum){
            $slesnum=0;
        }
        $where=array('goods_id'=>$goods_id,'delivery_time'=>array('EGT',$paytime-8*3600));
        $where['_string']='endval>='.$slesnum.' or '.$slesnum.'=0';
        $goods_presell_time=M('goods_presell_time')->where($where)->order('delivery_time asc')->find();
        if($goods_presell_time){
            $goods_presell_time['delivery_time']=local_date('Y-m-d H:i:s',$goods_presell_time['delivery_time']);
            return $goods_presell_time;
        }else{
        	$goods_presell_time = array('id'=>'','goods_id'=>'','endval'=>'','delivery_time'=>'');
            return $goods_presell_time;
        }
    }
}